<template>
  <div :class="[prefixCls]">
    <LcSvgIcon iconClass="home-icon" :class="`${prefixCls}-home`" />
    <ElBreadcrumb>
      <ElBreadcrumbItem v-for="route in breadcrumb" :key="route.path">
        <span>
          {{ route.meta.title || route.name }}
        </span>
      </ElBreadcrumbItem>
    </ElBreadcrumb>
  </div>
</template>
<script lang="ts" setup>
import type { Ref } from 'vue';
import { ref, watch, unref } from 'vue';
import { usePermissionStore } from '@/store/modules/permission';
import { getGlobalCls } from '@/utils/index';
import { useRouter } from 'vue-router';
import { LcSvgIcon } from '@/components/icon';

const { prefixCls } = getGlobalCls('container-multiple-header__breadcrumb');

const permissionStore = usePermissionStore();
const { currentRoute } = useRouter();

const breadcrumb: Ref<any[]> = ref([]);

watch([() => permissionStore.getMenuList.length, () => currentRoute.value], () => {
  updateBreadcrumb();
});

// listenerRouteChange((route) => {
//   isLoaded.value = true;
//   updateBreadcrumb(route);
// });

function updateBreadcrumb() {
  const { path } = unref(currentRoute);
  const menus = permissionStore.getMenuList;
  if (menus.length) {
    const currentBreadcrumb = findBreadcrumb(menus, path) || [];
    breadcrumb.value = currentBreadcrumb.length
      ? currentBreadcrumb
      : [
          {
            path: '/home/index',
            meta: {
              title: '首页'
            }
          }
        ];
  }
}

function findBreadcrumb(menuList: any[], path: string) {
  const loopFind = (
    menuList: any[] = [],
    path: string,
    pages: any[] = []
  ): {
    isFind: boolean;
    pages: any[];
  } => {
    const len = menuList.length;
    for (let i = 0; i < len; i++) {
      const page: any = menuList[i];
      if (page.path === path) {
        return {
          isFind: true,
          pages: [...pages, page]
        };
      }
      if (page.children && page.children.length) {
        const res = loopFind(page.children, path, [...pages, page]);
        if (res.isFind) return res;
      }
    }
    return {
      pages,
      isFind: false
    };
  };
  const { pages } = loopFind(menuList, path, []);
  return pages;
}
</script>
<style lang="scss">
$prefix-cls: #{config.$namespace}-container-multiple-header__breadcrumb;

.#{$prefix-cls} {
  display: flex;
  align-items: center;
  height: config.$breadcrumb-height;
  padding: 0 8px;
  &-home {
    margin-right: 4px;
  }
}
</style>
